using System;
using System.Messaging;
using MessageGateway;

namespace MessageGatewayMSMQ
{
    /* Returns an instance of IMessageReceiver and iMEssageSender based
     * on a given queue name. Will create a local queue matching this name
     * if it does not already exist.
     */

    public class MessageGatewayFactoryMSMQ : IMessageGatewayFactory
    {
        public virtual IMessageReceiver GetReceiverInstance(String queueName)
        {
            return new MessageReceiverMSMQ(FindQueue(queueName));
        }

        public virtual IMessageSender GetSenderInstance(String queueName)
        {
            return new MessageSenderMSMQ(FindQueue(queueName));
        }

        public virtual void Disconnect(string queueName)
        {
        }

        public virtual void Disconnect()
        {
        }

        protected MessageQueue FindQueue(String queueName)
        {
            if (queueName.IndexOf('\\') == -1)
            {
                queueName = ".\\private$\\" + queueName;
            }

            if (!MessageQueue.Exists(queueName))
            {
                try
                {
                    MessageQueue.Create(queueName);
                }
                catch (MessageQueueException e)
                {
                    // It might fail because the queue was created by another process. This is not an error.
                    if (e.MessageQueueErrorCode != MessageQueueErrorCode.QueueExists)
                    {
                        throw new ApplicationException(
                            "Could not create queue. Make sure the Message Queuing service is running.");
                    }
                }
            }
            return new MessageQueue(queueName);
        }
    }
}